package com.ugoodtech.mdcc.client.service.impl;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.controller.RequestObject.StationResponse;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.service.UserProfilesService;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.repository.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserProfilesServiceImpl implements UserProfilesService {

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;

    @Autowired
    private ComplaintReportDataRepository complaintReportDataRepository;

    @Autowired
    private ComplaintSolutionDataRepository complaintSolutionDataRepository;

    @Autowired
    private ComplaintReportRepository complaintReportRepository;

    /**
     * 关键字搜索用户
     *
     * @param userName
     * @return
     */
    @Override
    public JsonResponse findByName(String userName) {
        QUserProfile qUserProfile = QUserProfile.userProfile;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qUserProfile.deleted.eq(false));
        builder.and(qUserProfile.enabled.eq(true));
        builder.and(qUserProfile.user.userType.ne(UserType.customer));
        builder.and(qUserProfile.user.userType.ne(UserType.dealers));
        if (StringUtils.isNotEmpty(userName)) {
            builder.and(qUserProfile.realName.like("%" + userName + "%"));
        }
        List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(builder);
        if (userProfileList == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到类似的人");
        }
        List<StationResponse> list = toObjectList(userProfileList);
        return JsonResponse.successResponseWithData(list);
    }

    private List<StationResponse> toObjectList(List<UserProfile> userProfileList) {
        List<StationResponse> list = new ArrayList<>();
        for (UserProfile user : userProfileList) {
            StationResponse response = new StationResponse();
            response.setId(user.getUser().getId());
            response.setName(user.getRealName());
            list.add(response);
        }
        return list;
    }

    @Override
    public JsonResponse getUserName(String userName, String province, String brand) {
        QUserProfile qUserProfile = QUserProfile.userProfile;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qUserProfile.deleted.eq(false));
        builder.and(qUserProfile.enabled.eq(true));
        builder.and(qUserProfile.user.userType.ne(UserType.customer));
        builder.and(qUserProfile.user.userType.ne(UserType.dealers));
        if (StringUtils.isNotEmpty(userName)) {
            builder.and(qUserProfile.realName.like("%" + userName + "%"));
        }
        if (StringUtils.isNotEmpty(province)) {
            builder.and(qUserProfile.nationList.any().province.eq(province));
        }
        if (StringUtils.isNotEmpty(brand)) {
            QuestionAnswerOption answerOption = questionAnswerOptionRepository.findComplaintBrandByName(brand);
            if (null != answerOption && !brand.equals("其他品牌")) {
                builder.and(qUserProfile.brandList.any().brandName.eq(brand));
            }
        }
        List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(builder);
        if (userProfileList == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到类似的人");
        }
        List<StationResponse> list = toObjectList(userProfileList);
        return JsonResponse.successResponseWithData(list);
    }

    @Override
    public JsonResponse checkUser(Long userId, String province, String brand, Long solutionId) {
        if (null != solutionId && solutionId != 0) {
            ComplaintReport complaintReport = complaintReportRepository.findOne(solutionId);
            if (null != complaintReport) {
                ComplaintReportData data =
                        complaintReportDataRepository.selectByQuestion(solutionId, 189L);
                if (null != data && StringUtils.isNotEmpty(data.getAnswerOther())) {
                    province = data.getAnswerOther();
                }
                data = complaintReportDataRepository.selectByQuestion(solutionId, 194L);
                if (null != data && StringUtils.isNotEmpty(data.getAnswerId())) {
                    if (data.getAnswerOther().indexOf("447") == -1) {
                        StringBuffer brandBuffer = new StringBuffer("");
                        for (String brandId : data.getAnswerId().split(",")) {
                            QuestionAnswerOption questionAnswerOption =
                                    questionAnswerOptionRepository.findOne(Long.valueOf(brandId));
                            if (null != questionAnswerOption && StringUtils.isNotEmpty(questionAnswerOption.getName())) {
                                brandBuffer.append(questionAnswerOption.getName() + ",");
                            }
                        }
                        brand = brandBuffer.toString();
                    }
                }
            }
        }
        boolean hasBrand = hasBrand(userId, brand);
        boolean hasProvince = hasProvince(userId, province);
        if (hasBrand || hasProvince) {
            return JsonResponse.successResponse();
        }
        return JsonResponse.errorResponseWithError("抱歉", "该人员无此权限！");
    }

    private boolean hasProvince(Long userId, String province) {
        QUserProfile qUserProfile = QUserProfile.userProfile;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qUserProfile.deleted.eq(false));
        builder.and(qUserProfile.enabled.eq(true));
        builder.and(qUserProfile.user.id.eq(userId));
        if (StringUtils.isNotEmpty(province)) {
            BooleanBuilder orBuilder = new BooleanBuilder();
            builder.and(qUserProfile.nationList.any().province.eq(province));
            builder.and(orBuilder);
            UserProfile userProfile = userProfileRepository.findOne(builder);
            if (null == userProfile) {
                return false;
            }
            return true;
        }
        return false;
    }

    private boolean hasBrand(Long userId, String brand) {
        QUserProfile qUserProfile = QUserProfile.userProfile;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qUserProfile.deleted.eq(false));
        builder.and(qUserProfile.enabled.eq(true));
        builder.and(qUserProfile.user.id.eq(userId));
        if (StringUtils.isNotEmpty(brand)) {
            BooleanBuilder orBuilder = new BooleanBuilder();
            for (String brandName : brand.split(",")) {
                orBuilder.or(qUserProfile.brandList.any().brandName.eq(brandName));
            }
            builder.and(orBuilder);
            UserProfile userProfile = userProfileRepository.findOne(builder);
            if (null == userProfile) {
                return false;
            }
            return true;
        }
        return false;
    }

}
